// import './App.css';
import React, { Component } from 'react';
import { Space, Table, Popconfirm, Button, Input, Divider, Form, Drawer, message,Select } from 'antd';
import axios from 'axios';
import { render } from '@testing-library/react';
import get from "../api/api"
import { nanoid } from "nanoid";

class First extends Component {
    formRef = React.createRef() //清空输入框内容
    formRef1 = React.createRef()
    formRef2 = React.createRef()
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            visible1: false,
            visible2: false,
            rowid: null,
            namee: null,
            text: null,
            image: null,
            options:[],
            optionss:[],
            imageUrl: "",
            bcidname:"",
            bcidnamee:"",
            columns2:[
                
            ],
            columns: [
                { title: '名字', dataIndex: 'xiangqing', key: 'xiangqing', },
                {
                    title: '图片', dataIndex: '', key: 'image', render: (record) => {

                        return record.image ? <img src={record.image} style={{ width: '100px', height: '100px' }} /> : <p>暂无图片</p>
                    }
                },
                { title: '材料', dataIndex: 'text', key: 'text' },
                { title: '其他', dataIndex: 'text2', key: 'text2' },
                { title: '类别', dataIndex: 'classsselect', key: 'classsselect', },
                { title: '创建者', dataIndex: 'people_id', key: 'people_id', },
                { title: '简介', dataIndex: 'price', key: 'price', },
                { title: '热搜', dataIndex: 'sou', key: 'sou' },
                { title: '筛选/分类', dataIndex: 'bcidname', key: 'bcidname' },
                {
                    title: '操作',
                    key: 'action',
                    render: (_, record) => (
                        <Space size="middle">
                            <a className="action-link" onClick={this.showDrawer1.bind(this, record)}>修改</a>
                            <Popconfirm title="确定要删除吗?" onConfirm={this.deleteData.bind(this, record.objectId)} onCancel={this.onClose.bind(this)} okText="确定" cancelText="取消" >
                                <a className="action-link" style={{ color: record.obsoleted ? '#1890ff' : '#fa8c16' }} >删除</a>
                            </Popconfirm>
                        </Space>
                    ),
                },
                {
                    title: '添加附属图片',
                    key: 'image',
                    render: (_, record) => (
                        <Space size="middle">
                            <a className="action-link" onClick={this.showDrawer2.bind(this, record)}>添加附属图片</a>

                        </Space>
                    ),
                },

            ],
            data: [], //储存axios获取到的数据
        }
    }
    
    
    
    //获取筛选/分类
    getbcid=()=>{
        get('https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/pcclass',
            {
                "X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'
            }
        )
            .then(res => {
                console.log(res)
                const options = this.state.columns2.map(res => ({
                    label: res.name,
                    value: res.bcid
                    
                  }))
                this.setState({
                    columns2: res.results,
                    
                    options

                })
              
                  console.log(options)
                console.log(this.state.columns2)
                // res.results.forEach((r, i) => {

                //     r.key = i;
                // });
            }).catch(error => {
                console.log(error)
            })
    }
    //获取大类分类
    getclass=()=>{
        get('https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/pushds',
            {
                "X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'
            }
        )
            .then(res => {
                console.log(res)
                const optionss =res.results.map(res => ({
                    label: res.name,
                    value: res.class
                    
                  }))
                this.setState({
                    // columns2: res.results,
                    
                    optionss

                })
              
               
            }).catch(error => {
                console.log(error)
            })
    }

    //关闭新增信息对话框
    onClose = () => {
        this.setState({
            imageUrl: "",
            visible: false
        });
        message.error('取消操作');
    };
    //关闭修改信息对话框
    onClose1 = () => {
        this.setState({
            visible1: false
        });
        message.error('取消操作');
    };
    onClose2 = () => {
        this.setState({
            visible2: false
        });
        message.error('取消操作');
    };
    //显示新增信息抽屉
    showDrawer = () => {
        this.setState({
            visible: true
        });
    };
    //显示修改信息抽屉
    showDrawer1 = (r) => {
        // console.log(r.objectId)
        this.setState({
            visible1: true,

            rowid: r.objectId,
        })
        // console.log(this.rowid)
        setTimeout(() => { this.formRef1.current.setFieldsValue(r) }, 0);
    }; //设置 0 毫秒延迟回显数据
    //显示修改信息抽屉
    showDrawer2 = (r) => {
        // console.log(r)
        this.setState({
            visible2: true,
            rowid: r.objectId,
            namee: r.xiangqing
        });
    };

    //将数据显示在初始页面
    componentDidMount() {
        this.readData()
        this.getbcid()
        this.getclass()
    }

    //实现读取数据——————get
    readData() {
        get('https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs',
            {
                "X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'
            }
        )
            .then(res => {
                console.log(res)
                this.setState({
                    data: res.results

                })
                res.results.forEach((r, i) => {

                    r.key = i;
                });
            }).catch(error => {
                console.log(error)
            })
    }

    //新增信息时的Input输入框事件
    handleChange = (e) => {
        console.log(e)
        this.setState({
            [e.target.id]: e.target.value
        })
    }
    //select选择框
    handleChangee = (e) => {
        console.log(e)
        const selectedOption = this.state.options.find(option => option.value === e);
        this.setState({
            bcid: e,
            bcidname:selectedOption.label
        })
    }
    //大类select
    handleChangeee = (e) => {
        console.log(e)
        const selectedOption = this.state.optionss.find(option => option.value === e);
        this.setState({
            classs: e,
            bcidnamee:selectedOption.label
        })
    }
    //修改信息时的Input输入框事件
    handleChange1 = (e) => {
        this.setState({
            [e.target.id]: e.target.value
        })
    }

    //新增数据——————post
    //新增、修改数据时提交失败时的提示信息
    onFinishFailed = (errorInfo) => {
        console.log(this.state)
        // console.log('Failed:', this.state.imageUrl);
        message.error("按照格式要求输入")
    };
    handleSubmit = (event) => {


        // 上传图片到LeanCloud
        // const formData = new FormData();
        // formData.append('file', this.state.image);
        // formData.append('name', this.state.image.name);


    }
    postData = () => {
        // console.log(this.state)
        const formData = new FormData();
        formData.append('file', this.state.image);
        formData.append('name', this.state.image.name);
        axios.post('https://api.leancloud.cn/1.1/files/file', formData, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'image/jpeg'
            }
        }).then(response => {
            console.log(response)
            axios.post("https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs", {
                Id: nanoid(),
                xiangqing: this.state.xiangqing,
                image: response.data.url,
                classs: this.state.classs,
                classsselect:this.state.bcidnamee,
                people_id: this.state.people_id,
                price: this.state.price,
                text: this.state.text,
                text2: this.state.text2,
                bcid: this.state.bcid,
                bcidname:this.state.bcidname
            }, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json'
                }
            }).then(res => {
                message.success('添加成功');
                // console.log('添加成功')
                this.readData()
                
                this.setState({
                    visible: false,
                    image: null,
                    imageUrl: null
                });
                this.formRef.current.resetFields() //新增成功后清空输入框中的数据，避免下次点击新增时出现上次输入的数据
            }).catch(error => {

                message.error("按照格式要求输入")
                console.log(this.state)

            });
        })



    }

    //添加附属图片
    postDataf = (r) => {
        // console.log(this.state)
        const formData = new FormData();
        formData.append('file', this.state.image);
        formData.append('name', this.state.image.name);
        axios.post('https://api.leancloud.cn/1.1/files/file', formData, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'image/jpeg'
            }
        }).then(response => {
            console.log(response)
            console.log(r)

            axios.post("https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image", {
                name: this.state.namee,
                image_id: this.state.rowid,
                image_url: response.data.url,

            }, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json'
                }
            }).then(res => {
                message.success('添加成功');
                // console.log('添加成功')
                this.readData()
                this.setState({
                    visible2: false,
                    imageUrl: null,
                    image: null
                });
                this.formRef2.current.resetFields() //新增成功后清空输入框中的数据，避免下次点击新增时出现上次输入的数据
            }).catch(error => {

                message.error("按照格式要求输入111")
                // console.log(this.state)


            });
        })



    }


    //上传图片
    handleChangeimage = (event) => {
        const file = event.target.files[0];
        const reader = new FileReader();

        reader.onloadend = () => {
            this.setState({
                image: file
            })


            this.setState({
                imageUrl: reader.result
            })
        };

        if (file instanceof Blob) {
            reader.readAsDataURL(file);
        }



    };
    // // 实现删除————————delete
    deleteData = (id) => {
        console.log(id)
        axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${id}`, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'

            }
        }) //id前面的 / 不能省略
            .then(res => {
                message.success('删除成功');
                // console.log('删除成功')
                this.readData()
            }).catch(e => {
                message.success("删除失败了，请查看！！！")
            })
    };

    //实现按照姓名查询数据
    queryfn = (e) => {
        console.log(e)
        this.state.text = e.target.value
        console.log(this.state.text)
        window.timer = setTimeout(() => {
            // let data = this.state.data.filter(r => r.xiangqing.includes(this.state.text))
            if (this.state.text !== null) {

                this.readData();
            }

        })

    }
    //点击查询
    text = () => {
        clearTimeout(window.timer)  //防抖查询
        window.timer = setTimeout(() => {
            console.log()
            let data = this.state.data.filter(r => r.xiangqing ? r.xiangqing.includes(this.state.text) : null)
            if (data.length !== 0) {

                this.setState({
                    data
                })
            } else {
                let data = ""
                this.setState({
                    data
                })
            }


        }, 500)
    }


    //实现修改数据——put或patch
    updateData = () => {
        console.log(this.state)
        axios.put(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${this.state.rowid}`, {
            xiangqing: this.state.xiangqing,
            class: this.state.classs,
            price: this.state.price,
            bcid: this.state.bcid,
            text: this.state.text,
            text2: this.state.text2

        }, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'

            }
        }).then(res => {
            message.success('修改成功');
            console.log(res)
            this.readData()
            this.setState({
                visible1: false
            });
        }).catch(error => {
            message.error("按照格式要求输入")
        })
        this.formRef1.current.resetFields() //修改成功后清空输入框中的数据
    }

    render() {
        let data = this.state.data;
        let columns = this.state.columns;
        let { xiangqing, imageUrl, classs, people_id, price, bcid, text, text2 } = this.state;
        return (
            <div className="App">
                <Button type="primary" onClick={this.showDrawer.bind(this)} >添加信息 </Button>
                <Input placeholder="请根据姓名查找信息" style={{ marginLeft: '10px', width: '20%' }} onInput={this.queryfn} onKeyPress={this.text} />
                <Button type="primary" onClick={this.text} >查询 </Button>
                <Divider plain>人员信息表格</Divider>
                <Table columns={columns} dataSource={data} pagination={{ pageSize: 10 }} >   </Table>

                <Drawer title="添加个人信息" onClose={this.onClose} visible={this.state.visible}>
                    <Form ref={this.formRef} onFinish={this.postData} onFinishFailed={this.onFinishFailed} autoComplete="off" >
                        <Form.Item
                            name="xiangqing"
                            label="名字"
                            rules={[{ required: true, message: '请输入名字', },]} >
                            <Input placeholder="请输入您的姓名" id="xiangqing" value={xiangqing} onChange={this.handleChange} title='输入2-6位中文汉字' />
                        </Form.Item>
                        <Form.Item
                            name="image"
                            label="图片"
                            rules={[{ required: false, message: '图片', },]}  >
                            <Input placeholder="图片" type='file' id="image" onChange={this.handleChangeimage} title='图片' />

                            <img className='pushimage' src={imageUrl} style={{ maxWidth: '200px' }} alt="商品图片" />
                        </Form.Item>
                        {/* <Form.Item
                            name="classs"
                            label="类别"
                            rules={[{ required: true, message: '类别', },]} >
                            <Input placeholder="类别" id="classs" value={classs} onChange={this.handleChange} title='输入1-120之间的数字' />
                        </Form.Item> */}
                        <Form.Item>
                             <Space wrap>
                            <Select
                                defaultValue="请选择"
                                id='classs'
                                style={{ width: 120 }}
                                
                                onChange={this.handleChangeee}
                                options={this.state.optionss}
                            />
                        </Space>
                        </Form.Item>
                        <Form.Item
                            name="text"
                            label="材料"
                            rules={[{ required: true, message: '材料', },]} >
                            <Input placeholder="材料" id="text" value={text} onChange={this.handleChange} title='输入1-120之间的数字' />
                        </Form.Item>
                        <Form.Item
                            name="text2"
                            label="其他"
                            rules={[{ required: true, message: '其他', },]} >
                            <Input placeholder="其他" id="text2" value={text2} onChange={this.handleChange} title='输入1-120之间的数字' />
                        </Form.Item>
                        <Form.Item
                            name="people_id"
                            label="创建者"
                            rules={[{ required: true, message: '创建者', },]} >
                            <Input placeholder="创建者" id="people_id" value={people_id} onChange={this.handleChange} title='输入有效中文汉字' />
                        </Form.Item>
                        <Form.Item
                            name="price"
                            label="简介"
                            rules={[{ required: true, message: '简介', },]} >
                            <Input placeholder="简介" id="price" value={price} onChange={this.handleChange} title='输入1开头的11位有效手机号' />
                        </Form.Item>

                        {/* <Form.Item
                            name="bcid"
                            label="筛选/分类"
                            rules={[{ required: true, message: '筛选/分类', },]} >
                            <Input placeholder="筛选/分类" id="bcid" value={bcid} onChange={this.handleChange} title='输入1开头的11位有效手机号' />
                        </Form.Item> */}
                        <Form.Item>
                             <Space wrap>
                            <Select
                                defaultValue="请选择"
                                id='bcid'
                                style={{ width: 120 }}
                                
                                onChange={this.handleChangee}
                                options={this.state.options}
                            />
                        </Space>
                        </Form.Item>
                       

                        <Button onClick={this.onClose.bind(this)}>取消</Button>
                        <Button htmlType="submit" type="primary">完成 </Button>
                    </Form>
                </Drawer>

                <Drawer title="修改个人信息" onClose={this.onClose1} visible={this.state.visible1}>
                    <Form ref={this.formRef1} onFinish={this.updatpostData} onFinishFailed={this.onFinishFailed} autoComplete="off" >
                        <Form.Item
                            name="xiangqing"
                            label="姓名"
                            rules={[{ required: true, message: '名字', },]}     >
                            <Input placeholder="名字" id="xiangqing" value={xiangqing} onChange={this.handleChange1} title='输入2-6位中文汉字' />
                        </Form.Item>
                        <Form.Item
                            name="classs"
                            label="类别"
                            rules={[{ required: true, message: '类别', },]}  >
                            <Input placeholder="类别" id="classs" value={classs} onChange={this.handleChange1} title='输入男或女' />
                        </Form.Item>

                        <Form.Item
                            name="price"
                            label="简介"
                            rules={[{ required: true, message: '简介', },]}   >
                            <Input placeholder="简介" id="price" value={price} onChange={this.handleChange1} title='输入有效中文汉字' />
                        </Form.Item>
                        <Form.Item
                            name="bcid"
                            label="筛选/分类"
                            rules={[{ required: true, message: '筛选/分类', },]} >
                            <Input placeholder="筛选/分类" id="bcid" value={bcid} onChange={this.handleChange1} title='输入1开头的11位有效手机号' />
                        </Form.Item>
                        <Form.Item
                            name="text"
                            label="材料"
                            rules={[{ required: true, message: '材料', },]} >
                            <Input placeholder="材料" id="text" value={text} onChange={this.handleChange1} title='输入1开头的11位有效手机号' />
                        </Form.Item>
                        <Form.Item
                            name="text2"
                            label="其他"
                            rules={[{ required: true, message: '其他', },]} >
                            <Input placeholder="其他" id="text2" value={text2} onChange={this.handleChange1} title='输入1开头的11位有效手机号' />
                        </Form.Item>
                        <Button onClick={this.onClose1.bind(this)}>取消</Button>
                        <Button htmlType="submit" type="primary">完成 </Button>
                    </Form>
                </Drawer>

                <Drawer title="添加附属图片" onClose={this.onClose2} visible={this.state.visible2}>
                    <Form ref={this.formRef2} onFinish={this.postDataf} onFinishFailed={this.onFinishFailed} autoComplete="off" >
                        <Form.Item
                            name="image"
                            label="图片"
                            rules={[{ required: false, message: '图片', },]}  >
                            <Input placeholder="图片" type='file' id="image" onChange={this.handleChangeimage} title='图片' />

                            <img className='pushimage' src={imageUrl} style={{ maxWidth: '200px' }} alt="商品图片" />
                        </Form.Item>
                        <Button onClick={this.onClose1.bind(this)}>取消</Button>
                        <Button htmlType="submit" type="primary">完成 </Button>
                    </Form>
                </Drawer>
            </div>
        );
    }
}
export default First;

